package com.gs.process.core.interceptor;

import com.alibaba.fastjson.JSON;
import com.gs.process.core.user.ProcessUserService;
import com.shallowUniverse.model.Result;
import lombok.AllArgsConstructor;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author: Shuai Guo
 * @description:
 * @date: 2021/9/26
 * @version: 1.0
 */
@AllArgsConstructor
public class WebInterceptor implements HandlerInterceptor {

    private final ProcessContextManager manager;
    private final ProcessUserService processUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        //判断是否是推送数据接口
        if (request.getRequestURI().contains("/receive")) {
            return true;
        }
        //注入用户
        manager.autoWriedUser();
        Result<Object> result = new Result<>();
        //判断是否是流程注册相关的接口
        if (request.getRequestURI().contains("/process")) {
            //判断是否添加了权限拦截器
            if (CollectionUtils.isEmpty(manager.getProcessPermissionInterceptors())) {
                return true;
            }
            //定义结果变量
            AtomicBoolean fact = new AtomicBoolean(true);
            //执行
            manager.getProcessPermissionInterceptors().forEach(interceptor -> {
                if (!interceptor.permissionCheck(processUserService.get())) {
                    fact.set(false);
                }
            });
            //判断是否有权限
            if (!fact.get()) {
                result.setMessage("权限不足").setCode(403);
                response.getWriter().write(JSON.toJSONString(result));
                return false;
            }
        }
        //判断用户是否为空
        if (ObjectUtils.isEmpty(processUserService.get())) {
            result.setMessage("未登录").setCode(401);
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除用户避免缓存
        processUserService.clear();
    }
}
